


#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/select.h>
#include <unistd.h>
#include <errno.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define MAXLINE 1500

int readable_timeout(int fd,int sec){

    fd_set select_set;
    FD_ZERO(&select_set);

    struct timeval tv;

    FD_SET(fd,&select_set);

    tv.tv_sec = sec;
    tv.tv_usec = 0;

    // > 0 if descriptor is readable
    return (select(fd+1,&select_set,NULL,NULL,&tv));
}


void dg_cli(FILE * fp, int sockfd, const struct sockaddr * sa, socklen_t servlen){


    size_t n = 0;

    char sendline[MAXLINE], recvline[MAXLINE + 1];

    bzero(sendline, MAXLINE);
    bzero(recvlien, MAXLINE + 1);

    while(fgets(sendline, MAXLINE, fp) != NULL){

	sendto(sockfd, sendline, strlen(sendline), 0, sa, servlen);

	if(readable_timeout(sockfd, 5) == 0){

	    fprintf(stderr, "socket timeout\n");
	}else{

	    n  = recvfrom(sockfd, recvline, MAXLINE, 0, NULL, NULL);
	    recvline[n] = 0; /* null terminate  */
	    fputs(recvline, stdout);

	}
    }
}

